using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using DM.DAO;

namespace DM.Web.Admin
{
    public partial class QuanLyAnhQC : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                BindingDataList();
            }
        }

        protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            Label fileExt = (Label)e.Item.FindControl("LabelFileExtention");
            if (fileExt.Text == "swf")
            {
                Panel panelImage = (Panel)e.Item.FindControl("labelImage");
                panelImage.Visible = false;
            }
            else
            {
                Panel panelFlash = (Panel)e.Item.FindControl("labelFlash");
                panelFlash.Visible = false;
            }
        }

        protected void buttonChangeLink_Click(object sender, EventArgs e)
        {
            FileInfo xmlFile = new FileInfo(MapPath("../../Photos/QuangCao/catalogimage.xml"));
            Button button = (Button)sender;
            TextBox textBoxLink = (TextBox)button.Parent.FindControl("textBoxLink");
            Label label = (Label)button.Parent.Parent.FindControl("LabelFileExtention");
            string urlImage = label.ToolTip;
            if (xmlFile.Exists)
            {
                try
                {
                    XmlDocument doc = new XmlDocument();
                    doc.Load(MapPath("../../Photos/QuangCao/catalogimage.xml"));
                    XmlNode noteCatalog = doc.DocumentElement;
                    foreach (XmlNode nodeImage in noteCatalog.ChildNodes)
                    {
                        bool finded = false;
                        foreach (XmlNode node in nodeImage.ChildNodes)
                        {
                            if (node.Name == "Name" && node.InnerText == urlImage) finded = true;
                        }
                        if (finded == true)
                            foreach (XmlNode node in nodeImage.ChildNodes)
                            {
                                if (node.Name == "Link")
                                {
                                    if (textBoxLink.Text.Contains("http://"))
                                    { node.InnerText = textBoxLink.Text; }
                                    else
                                    {
                                        node.InnerText = "http://" + textBoxLink.Text;
                                    }
                                }
                            }
                    }
                    doc.Save(MapPath("../../Photos/QuangCao/catalogimage.xml"));
                    Response.Redirect(Request.UrlReferrer.ToString(), true);
                }
                catch (Exception ex)
                {

                }
            }
        }

        protected void buttonDelete_Click(object sender, EventArgs e)
        {
            FileInfo xmlFile = new FileInfo(MapPath("../../Photos/QuangCao/catalogimage.xml"));
            Button button = (Button)sender;
            Label urlImageLabel = (Label)button.Parent.Parent.FindControl("urlImage");
            Label ext = (Label)button.Parent.Parent.FindControl("labelFileExtention");
            int fileIndex = Int32.Parse(ext.ToolTip);
            string urlImage = urlImageLabel.Text;
            FileInfo image = new FileInfo(MapPath(urlImage));
            DirectoryInfo directoryQuangCao = image.Directory;
            if (File.Exists(MapPath(urlImage)))
                File.Delete(MapPath(urlImage));
            foreach (FileInfo file in directoryQuangCao.GetFiles())
            {
                if (file.Name == "catalogimage.xml")
                {
                    continue;
                }
                if (Int32.Parse(file.Name.Substring(0, 1)) > Int32.Parse(image.Name.Substring(0, 1)))
                {
                    file.MoveTo(MapPath("../../Photos/QuangCao/" + (Int32.Parse(file.Name.Substring(0, 1)) - 1).ToString() + "." + ext.Text));
                }
            }

            //Su ly xml
            if (xmlFile.Exists)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(MapPath("../../Photos/QuangCao/catalogimage.xml"));
                XmlNode noteCatalog = doc.DocumentElement;
                int ten = 1;

                //Xoa bo XmlNode tuong ung voi file da xoa
                foreach (XmlNode nodeImage in noteCatalog.ChildNodes)
                {
                    foreach (XmlNode node in nodeImage.ChildNodes)
                    {
                        if (node.Name == "urlImage" && node.InnerText == urlImage)
                        {
                            noteCatalog.RemoveChild(nodeImage);
                            break;
                        }
                    }
                }

                //Chinh lai ten file va index cua xml file
                //chinh urlimage
                foreach (XmlNode nodeImage in noteCatalog.ChildNodes)
                {
                    if (Int32.Parse(nodeImage["urlImage"].InnerText.Substring(nodeImage["urlImage"].InnerText.LastIndexOf(".") - 1, 1)) > Int32.Parse(urlImage.Substring(urlImage.LastIndexOf(".") - 1, 1)))
                    {
                        string url = nodeImage["urlImage"].InnerText.Substring(nodeImage["urlImage"].InnerText.LastIndexOf(".") - 1, 1);
                        nodeImage["urlImage"].InnerText = nodeImage["urlImage"].InnerText.Replace(url, (Int32.Parse(url) - 1).ToString());
                    }
                    if (Int32.Parse(nodeImage["Name"].InnerText) > fileIndex)
                    {
                        int newindex = Int32.Parse(nodeImage["Name"].InnerText) - 1;
                        nodeImage["Name"].InnerText = newindex.ToString();
                    }
                }
                doc.Save(MapPath("../../Photos/QuangCao/catalogimage.xml"));
            }
            Response.Redirect(Request.UrlReferrer.ToString(), true);
        }

        protected void buttonUp_Click(object sender, EventArgs e)
        {
            Button buttonUp = (Button)sender;
            Label labelExt = (Label)buttonUp.Parent.Parent.FindControl("LabelFileExtention");
            int index = Int32.Parse(labelExt.ToolTip);
            if (index > 1)
                MoveFile(true, index);
        }

        protected void buttonDown_Click(object sender, EventArgs e)
        {
            Button buttonUp = (Button)sender;
            Label labelExt = (Label)buttonUp.Parent.Parent.FindControl("LabelFileExtention");
            int index = Int32.Parse(labelExt.ToolTip);
            DirectoryInfo dir = new DirectoryInfo(MapPath("../../Photos/QuangCao"));
            int numberfile = dir.GetFiles().Length;
            if (index < numberfile - 1)
            {
                MoveFile(false, index);
            }
        }

        protected void ButtonUpload_Click(object sender, EventArgs e)
        {
            Common.UploadQuangCao(FileUpload, FileNameUpload(), FileExtentionUpload());
            DirectoryInfo dirQuangCao = new DirectoryInfo(MapPath("../../Photos/QuangCao"));
            if (dirQuangCao.GetFiles().Length < 9)
            {
                BindingDataList();
                Response.Redirect(Request.UrlReferrer.ToString(), true);
            }
            else
            {
                Common.Show("Bạn chỉ được up 9 quảng cáo tối đa!", Request.UrlReferrer.ToString());
            }
        }

        //Find filename to upload
        protected string FileNameUpload()
        {
            DirectoryInfo QuangCaoDirectory = new DirectoryInfo(MapPath("../../Photos/QuangCao"));
            FileInfo[] listFile = QuangCaoDirectory.GetFiles();
            int fileName = listFile.Length;
            return fileName == 0 ? ("Photos/QuangCao/1." + FileExtentionUpload()) : "Photos/QuangCao/" + fileName + "." + FileExtentionUpload();
        }
        //Find fileExtention to upload
        protected string FileExtentionUpload()
        {
            if (FileUpload.HasFile)
            {
                string filePath = FileUpload.FileName.Substring(FileUpload.FileName.Length - 3, 3);
                return filePath;
            }
            return "";
        }


        /// <summary>
        /// Ham doi ten file, chi dung cho up and down button;
        /// </summary>
        /// <param name="up">true la giam chi so file, false la tang chi so file</param>
        /// <param name="index">Vi tri xap xep cua anh</param>
        protected void MoveFile(bool up, int index)
        {
            //FileInfo image = new FileInfo(MapPath(urlFile));
            int index2 = up ? index - 1 : index + 1;
            XmlDocument doc = new XmlDocument();
            doc.Load(MapPath("../../Photos/QuangCao/catalogimage.xml"));

            //process catalogimage.xml

            XmlNodeList listNodeImage = doc.SelectNodes("catalog/image");//List tat ca cac element <image>
            XmlNode Node1 = null;
            XmlNode Node2 = null;
            foreach (XmlNode node in listNodeImage)
            {
                if (node["Name"].InnerText == index.ToString())
                {
                    Node1 = node;
                }
                if (node["Name"].InnerText == index2.ToString())
                {
                    Node2 = node;
                }
            }

            Node1["Name"].InnerText = index2.ToString();
            Node2["Name"].InnerText = index.ToString();
            doc.Save(MapPath("../../Photos/QuangCao/catalogimage.xml"));
            BindingDataList();
            Response.Redirect(Request.UrlReferrer.ToString(), true);
        }


        protected void BindingDataList()
        {
            FileInfo xmlFile = new FileInfo(MapPath("../../Photos/QuangCao/catalogimage.xml"));
            if (xmlFile.Exists)
            {
                DataSet dataSet = new DataSet();
                dataSet.ReadXml(MapPath("../../Photos/QuangCao/catalogimage.xml"));
                if (dataSet.Tables.Count != 0)
                {
                    dataSet.Tables[0].DefaultView.Sort = "Name";
                    DataView dataView = dataSet.Tables[0].DefaultView;
                    DataList1.DataSource = dataView;
                    DataList1.DataBind();
                }
                else
                {
                    DataList1.Enabled = false;
                }
            }
            else
            {
                DataList1.Enabled = false;
            }
        }

    }
}
